package com.projet.segmiMap.activities;


import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.projet.segmiMap.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.Polygon;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.projet.segmiMap.model.Etage;
import com.projet.segmiMap.model.Lieu;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends FragmentActivity implements GoogleMap.OnInfoWindowClickListener {
    private SlidingMenu slidingMenu;
    private GoogleMap mMap;
    private static final LatLng BATG = new LatLng(48.903017, 2.215565);
    private static final float ANGLE = 40;
    private static final float ZOOM_DEFAUT = 18;
    private static final float ZOOM_SELECT = 19;
    private List<Etage> etages = new ArrayList<Etage>();
    private int etageCourant = 0;

    public SlidingMenu getSlidingMenu() {
        return slidingMenu;
    }

    /**
     * Permet la création de la carte au démarrage de l'application
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(BATG)
                .tilt(ANGLE)
                .zoom(ZOOM_DEFAUT)
                .build();
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        mMap.setMyLocationEnabled(true);
        FloorBuilder floorBuilder = new FloorBuilder(mMap, this);

        mMap = floorBuilder.getmMap();
        etages = floorBuilder.getFloors();
        for (int i = 1; i < etages.size(); i++) {
            setVisible(etages.get(i), false);
        }

        mMap.setInfoWindowAdapter(new SegmiWindow(getLayoutInflater()));
        mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                Etage et = etages.get(etageCourant);
                for (Marker m : et.getMarkers()) {
                    m.setVisible(cameraPosition.zoom >= ZOOM_DEFAUT);
                }
            }
        });
        mMap.setOnInfoWindowClickListener(this);
        setUpMapIfNeeded();

        //Définition des propriétés du menu
        slidingMenu = new SlidingMenu(this);
        slidingMenu.setMode(SlidingMenu.LEFT);
        slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        slidingMenu.setFadeDegree(0.35f);
        slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        slidingMenu.setMenu(R.layout.slidingmenu);
        if (Build.VERSION.SDK_INT >= 11)
            getActionBar().setDisplayHomeAsUpEnabled(true);

        //Affichage du menu lors du clique sur le boutton "Menu"
        RelativeLayout b = (RelativeLayout) findViewById(R.id.menu);
        b.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                getSlidingMenu().toggle();
            }
        });

        //Début Listener sur les étages
        ArrayList<ImageView> etages = new ArrayList<ImageView>();
        etages.add((ImageView) findViewById(R.id.rdc));
        etages.add((ImageView) findViewById(R.id.etage1));
        etages.add((ImageView) findViewById(R.id.etage2));
        etages.add((ImageView) findViewById(R.id.etage3));
        etages.add((ImageView) findViewById(R.id.etage4));
        etages.add((ImageView) findViewById(R.id.etage5));
        etages.add((ImageView) findViewById(R.id.etage6));
        etages.add((ImageView) findViewById(R.id.entre_sol));

        View.OnClickListener choixEtage = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.rdc:
                        findLocation("0");
                        getSlidingMenu().toggle();
                        break;
                    case R.id.etage1:
                        findLocation("1");
                        getSlidingMenu().toggle();
                        break;
                    case R.id.etage2:
                        findLocation("2");
                        getSlidingMenu().toggle();
                        break;
                    case R.id.etage3:
                        findLocation("3");
                        getSlidingMenu().toggle();
                        break;
                    case R.id.etage4:
                        findLocation("4");
                        getSlidingMenu().toggle();
                        break;
                    case R.id.etage5:
                        findLocation("5");
                        getSlidingMenu().toggle();
                        break;
                    case R.id.etage6:
                        findLocation("6");
                        getSlidingMenu().toggle();
                        break;
                    case R.id.entre_sol:
                        findLocation("7");
                        getSlidingMenu().toggle();
                        break;
                    default:
                }
            }
        };
        for (ImageView v : etages) {
            v.setOnClickListener(choixEtage);
        }


        //Fin listener Etages
        final AutoCompleteTextView v = (AutoCompleteTextView) findViewById(R.id.recherche);
        ArrayList<String> autoCompletion = new ArrayList<String>();
        //lecture du fichier d'auto complétion
        try {
            InputStream ips = getResources().openRawResource(R.raw.autocompletion);
            InputStreamReader ipsr = new InputStreamReader(ips);
            BufferedReader br = new BufferedReader(ipsr);
            String ligne;
            while ((ligne = br.readLine()) != null) {
                autoCompletion.add(ligne);
            }

            br.close();
        } catch (Exception e) {
            Log.v("myapp", e.toString());
        }
        autoCompletion.toArray();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, autoCompletion);
        v.setAdapter(adapter);

        v.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //Cacher le clavier lorsqu'on appuie sur Entrer
                if (event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    in.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
                return false;
            }
        });
        Button find = (Button) findViewById(R.id.find);
        find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String location = v.getText().toString();
                if (location != null && !location.equals("")) {
                    findLocation(location);
                    //Cacher le clavier
                    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    in.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    getSlidingMenu().toggle();
                }
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    private void setUpMapIfNeeded() {
        if (mMap != null) {
            return;
        }

        if (mMap == null) {
            return;
        }

    }

    private void findLocation(String location) {
        int valeurEtage = -1;
        try {
            valeurEtage = Integer.parseInt(location);
        } catch (NumberFormatException e) {
            Log.v("myapp", e.getMessage());
        }

        for (Etage c : etages) {

            if (c.getNom().equals(location) || c.getEtage() == valeurEtage) {
                changerEtage(c.getEtage());
                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(BATG)
                        .tilt(ANGLE)
                        .zoom(ZOOM_DEFAUT)
                        .build();
                mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            }
            for (Lieu l : c.getLieux()) {
                if (location.length() == 1) {
                    location = new String("amphi " + location);
                }
                Matcher m = Pattern.compile(location.toLowerCase()).matcher(l.getNom().toLowerCase());
                if (l.getNom().equalsIgnoreCase(location) || m.find()) {
                    if (l.getEtage() == etageCourant) {
                        CameraPosition cameraPosition = new CameraPosition.Builder()
                                .target(l.getMarqueur().getPosition())
                                .tilt(ANGLE)
                                .zoom(ZOOM_SELECT)
                                .build();
                        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        l.getMarker().showInfoWindow();
                    } else {
                        changerEtage(l.getEtage());
                        CameraPosition cameraPosition = new CameraPosition.Builder()
                                .target(l.getMarqueur().getPosition())
                                .tilt(ANGLE)
                                .zoom(ZOOM_SELECT)
                                .build();
                        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        l.getMarker().showInfoWindow();
                    }
                }
            }
        }
    }

    public void setVisible(Etage c, boolean visible) {
        if (visible) {
            for (Marker m : c.getMarkers()) {
                m.setVisible(visible);
            }
            for (Polygon p : c.getElements()) {
                p.setVisible(visible);
            }
        } else {
            for (Marker m : c.getMarkers()) {
                m.setVisible(visible);
            }
            for (Polygon p : c.getElements()) {
                p.setVisible(visible);
            }
        }
    }

    private void changerEtage(int etage) {
        etageCourant = etage;
        for (Etage c : etages) {
            if (c.getEtage() == etage) {
                setVisible(c, true);
            } else {
                setVisible(c, false);
            }
        }
        ImageView imageEtage = (ImageView) findViewById(R.id.etageCourant);
        switch (etageCourant) {
            case 0:
                imageEtage.setImageResource(R.drawable.logo0);
                break;
            case 1:
                imageEtage.setImageResource(R.drawable.logo1);
                break;
            case 2:
                imageEtage.setImageResource(R.drawable.logo2);
                break;
            case 3:
                imageEtage.setImageResource(R.drawable.logo3);
                break;
            case 4:
                imageEtage.setImageResource(R.drawable.logo4);
                break;
            case 5:
                imageEtage.setImageResource(R.drawable.logo5);
                break;
            case 6:
                imageEtage.setImageResource(R.drawable.logo6);
                break;
            case 7:
                imageEtage.setImageResource(R.drawable.logoe);
                break;
            default:
                imageEtage.setImageResource(R.drawable.logo0);
                break;
        }

    }

    @Override
    public void onInfoWindowClick(Marker marker) {
        Toast.makeText(this, marker.getTitle(), Toast.LENGTH_LONG).show();
    }
}
